/**
 * 
 */
package com.idea.zd.sys.te;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.metaparadigm.jsonrpc.JSONRPCBridgeServletArgResolver;

import javax.swing.text.html.HTMLDocument;

/**
 * @author y.z
 */
public class PowerHttpClient {
	
	public static String doPost(String url,String bodyData,String token){
		return httpURLConnectionPOST(url,bodyData,token);
		
	}
	
	
	
	public static String httpURLConnectionPOST (String urlStr,String bodyData,String token) {  
	       try {    
	          
	           URL url = new URL(urlStr);  
	           // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  
	           // 此时cnnection只是为一个连接对象,待连接中  
	           
	           
	           HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
	           // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)  
	           connection.setDoOutput(true);  
	           // 设置连接输入流为true  
	           connection.setDoInput(true);  
	           // 设置请求方式为post  
	           connection.setRequestMethod("POST");  
	           // post请求缓存设为false  
	           connection.setUseCaches(false);  
	           // 设置该HttpURLConnection实例是否自动执行重定向  
	           connection.setInstanceFollowRedirects(true);  
	           // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)  
	           // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据  
	           // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】  
	           //addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}  
	           //connection.addRequestProperty("from", "sfzh");  //来源哪个系统  
	           //setRequestProperty添加相同的key会覆盖value信息  
	           //setRequestProperty方法，如果key存在，则覆盖；不存在，直接添加。  
	           //addRequestProperty方法，不管key存在不存在，直接添加。  
	           //connection.setRequestProperty("user", "user");  //访问申请用户  
	           InetAddress address = InetAddress.getLocalHost();   
	        String ip=address.getHostAddress();//获得本机IP  
	           //connection.setRequestProperty("ip",ip);  //请求来源IP  
	           //connection.setRequestProperty("encry", "123456");  
	           connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");  
	           //connection.setRequestProperty("Authorization", token);
	           //connection.
	           // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)  
	           connection.connect();  
	           // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  
	           System.out.println(connection.getOutputStream());
	           DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
	           // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444  
	           String parm =bodyData;  
	           //System.out.println("传递参数："+parm);
	           // 将参数输出到连接  
	           dataout.writeBytes(parm);  
	           // 输出完成后刷新并关闭流  
	           dataout.flush();  
	           dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)   
	           //System.out.println(connection.getResponseCode());  
	           // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)  
	           BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
	           String line;  
	           StringBuilder sb = new StringBuilder(); // 用来存储响应数据  
	             
	           // 循环读取流,若不到结尾处  
	           while ((line = bf.readLine()) != null) {  
	            //sb.append(bf.readLine());  
	            sb.append(line).append(System.getProperty("line.separator"));  
	           }  
	           bf.close();    // 重要且易忽略步骤 (关闭流,切记!)   
	           connection.disconnect(); // 销毁连接  
	           //System.out.println(sb.toString());
	           return sb.toString();
	       } catch (Exception e) {  
	           e.printStackTrace();  
	       }
	       return null;
	   }
	
	public static String Post(){
		//return HttpKit.get("https://oapi.dingtalk.com/department/li st?access_token=c454a452a88038ba8d66e5e2271ce5e4&id=1");
		//Map<String, Object> values = JSON.parseObject(HttpKit.get("https://oapi.dingtalk.com/gettoken?corpid=dingfbffe809817079dd&corpsecret=lzDu0c9P5G5KKIdjoP5yGZn1iS6Ey9Dcbb3Ct41MAuct6vAd99et1BTKFeTiaBgR"), Map.class);


		/*Set<String> set = values.keySet(); 
		for(String s:set) {
		 System.out.println(s+","+values.get(s));
		}*/


		
		//return HttpKit.get("https://oapi.dingtalk.com/gettoken?corpid=dingfbffe809817079dd&corpsecret=lzDu0c9P5G5KKIdjoP5yGZn1iS6Ey9Dcbb3Ct41MAuct6vAd99et1BTKFeTiaBgR");
		//return HttpKit.get("https://oapi.dingtalk.com/department/get?access_token=c454a452a88038ba8d66e5e2271ce5e4&id=25384368");
		//return HttpKit.get("https://oapi.dingtalk.com/department/list?access_token=af26c4f50b593a91995143867a3ee049");
		//String params = "{\"urls\":{\"http://app.fansiji.com/h5/iqiyi/\"},\"type\":\"dir\"}";


		Map<String,Object> params = new HashMap<>();
		String urls[] = new String[]{"http://app.fansiji.com/h5/iqiyi/"};
		params.put("urls",urls);
		params.put("type","dir");


		return doPost("https://purge.qingcdn.com/purge/purge?token=0f455652c965a46a59c95b4d7494bef4",JSON.toJSONString(params),null);
	}
	public static void main(String[] args) {

		String str = "[{\"出差事由\":\"1111\"},{\"总差旅天数\":\"2\"},[{\"出差部门\":\"IP创意部\",\"出差人员\":\"谢守惠\",\"出差地点\":\"11111\",\"出差时间\":\"2017-12-29  -  2017-12-30\"},{\"出差部门\":\"产品部\",\"出差人员\":\"叶全鑫\",\"出差地点\":\"1111\",\"出差时间\":\"2017-12-29  -  2017-12-30\"}]]";

		System.out.println(PowerHttpClient.getJson(str,""));
	}


	public static String getJson(String json,String result){
		Object objRet  = null;

		try{
			objRet	= JSONArray.parseArray(json);
		}catch (Exception e){
			objRet = JSONObject.parseObject(json,Map.class);
		}


		if(objRet.getClass().equals(JSONArray.class)){
			JSONArray jsonArray = (JSONArray)objRet;
			for(int k=0;k<jsonArray.size();k++){
				Object retJson = null;

				try{
					retJson =  JSONArray.parseArray(jsonArray.get(k).toString());
				}catch (Exception e){
					retJson = JSONObject.parseObject(jsonArray.get(k).toString(),Map.class);
				}





				if(retJson.getClass().equals(JSONArray.class)){
					result +=  getJson(retJson.toString(),"");


				}else{


					Set key = ((Map)retJson).keySet();

					Iterator iterator = key.iterator();

					while(iterator.hasNext()){
						Object tempKey = iterator.next();
						result += "key:"+tempKey+",value:"+((Map)retJson).get(tempKey)+"\n";
					}

				}

			}
		}else{

			Set key = ((Map)objRet).keySet();

			Iterator iterator = key.iterator();

			while(iterator.hasNext()){
				Object tempKey = iterator.next();
				result += "key:"+tempKey+",value:"+((Map)objRet).get(tempKey)+"\n";
			}

		}

		return result;
	}




}
